import { _get } from '@/utils/storage'

const hasPermission: any = {
  install(Vue: any, options: any) {
    Vue.directive('has', {
      inserted: (el: any, binding: any, vnode: any) => {
        // 节点权限处理，如果命中则不进行全局权限处理
        if(!filterNodePermission(el, binding, vnode)){
          filterGlobalPermission(el, binding, vnode)
        }
      }
    })
  }
}

/**
 * 全局权限控制
 */
export function filterNodePermission(el: any, binding: any, vnode: any) {
  // console.log('页面权限--NODE--')
  let permissionList: any[] = []
  try {
    let obj: any = vnode.context.$props.formData
    if (obj) {
      let bpmList: any[] = obj.permissionList
      for (let bpm of bpmList) {
        if (bpm.type !== '2') {
          permissionList.push(bpm)
        }
      }
    }
  } catch (e) {
    // console.log('页面权限--NODE--异常')
  }
  if (!permissionList || (permissionList && !permissionList.length)) {
    return false
  }
  let permissions = []
  for (var item of permissionList) {
    if (item.type !== '2') {
      permissions.push(item.action)
    }
  }
  if (!permissions.includes(binding.value)) {
    return false
  } else {
    for (let item2 of permissionList) {
      if (binding.value === item2.action) {
        return true
      }
    }
  }
  return false
}

/**
 * 全局权限控制
 */
export function filterGlobalPermission(el: any, binding: any, vnode: any) {
  // console.log('页面权限--Global--')

  let permissionList: any[] = []
  let allPermissionList: any[] = []

  let authList: any[] = _get('authData', 's')
  permissionList = authList && authList.filter((item: any) => item.type !== '2')
  
  let allAuthList: any[] = _get('allAuthData', 's')
  allPermissionList = allAuthList && allAuthList.filter((item: any) => item.type !== '2')
  
  // 设置全局配置是否有命中
  let invalidFlag: boolean = false // 无效命中
  if (allPermissionList && allPermissionList.length) {
    for (var itemG of allPermissionList) {
      if (binding.value === itemG.action) {
        if (itemG.status === '0') {
          invalidFlag = true
          break
        }
      }
    }
  }
  if (invalidFlag) {
    return
  }
  if (!permissionList || (permissionList && !permissionList.length)) {
    el.parentNode && el.parentNode.removeChild(el)
    return
  }
  let permissions = []
  for (var item of permissionList) {
    if (item.type !== '2') {
      permissions.push(item.action)
    }
  }
  if (!permissions.includes(binding.value)) {
    el.parentNode && el.parentNode.removeChild(el)
  }
}

export default hasPermission
